package com.qf.dao.Impl;/*
    Dell
    2021/10/9
    12:00
*/

import com.qf.dao.CategoryDao;
import com.qf.entiy.Category;
import com.qf.entiy.Product;
import com.qf.util.DruidUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class CategoryDaoImpl implements CategoryDao {
    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<Category> showAll() {
        try {
            return queryRunner.query(DruidUtil.getConnection(),"select * from Category;", new BeanListHandler<>(Category.class));
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+":查询所有机构出现了异常");
        }
    }

    @Override
    public Product showById(Integer id) {
        try {
            String sql = "select p.id, p.pname, c.name, date, vender, price, type, p.cid from product as p inner join category c on p.cid = c.id where p.id = ?;";
            Map<String, Object> query = queryRunner.query(DruidUtil.getConnection(), sql, new MapHandler(),id);
            if(query==null){
                return null;
            }
            Product product = new Product();
            Category category = new Category();
            BeanUtils.populate(product, query);
            BeanUtils.populate(category, query);
            product.setCategory(category);
            return product;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage()+"查询单个药品出现异常");
        }
    }
}
